
import { RdbMapper } from './RdbMapper';
import relationalStore from '@ohos.data.relationalStore';
import { Log } from '../Log';
import { Constants } from '../Constants';
import { ColumnInfo } from '../bean/ColumnInfo';
import { TableUtil } from '../../utils/TableUtil';
export class RdbMapperImpl implements RdbMapper {
  private mDBName: string;
  private rdbStore: relationalStore.RdbStore = null;
  private storeConfig: relationalStore.StoreConfig;

  constructor(dbName: string) {
    this.mDBName = dbName;
  }

  getDBName(): string {
    return this.mDBName;
  }

  getRdb(context: any): Promise<RdbMapper> {
    this.storeConfig = {
      name: this.mDBName,
      securityLevel: relationalStore.SecurityLevel.S1
    };
    return new Promise<RdbMapper>((resolve, reject) => {
      relationalStore.getRdbStore(context, this.storeConfig).then(dbStore => {
        this.rdbStore = dbStore;
        // resolve(this);
      }).catch(err => {
        Log.error(Constants.LOG_TAG_NAME, `initRdb failed. Cause: ${JSON.stringify(err)}`);
        reject(err);
      })
    })
  }

  executeSql(sql: string): Promise<void> {
    return this.rdbStore.executeSql(sql);
  }

  createTable(tableName: string, columns: Array<ColumnInfo>): Promise<void> {
    let createTableSql = TableUtil.createTableSql(tableName, columns);
    return this.executeSql(createTableSql);
  }

  deleteTable(tableName: string): Promise<void> {
    let deleteTableSql = TableUtil.deleteTableSql(tableName);
    return this.executeSql(deleteTableSql);
  }

  addTableColumn(tableName: string, column: ColumnInfo): Promise<void> {
    let addTableColumnSql = TableUtil.addTableColumnSql(tableName, column);
    return this.executeSql(addTableColumnSql);
  }

  insert(tableName: string, values: relationalStore.ValuesBucket | Array<relationalStore.ValuesBucket>): Promise<number> {
    return new Promise<number>((resolve, reject) => {
      if (!values) {
        reject(0);
        return;
      }
      if (Array.isArray(values)) {
        this.rdbStore.beginTransaction();

      }
    })
  }

  private saveArray(tableName: string, values: Array<relationalStore.ValuesBucket>): Promise<number> {

  }
}